<?php

namespace lc\middleware;

use app\Auth;
use lc\cache\redis\Redis;
use lc\helpers\Helper;
use lc\helpers\Response;
use think\facade\Config;
use think\facade\Cookie;

class Lock
{
    public function handle($request, \Closure $next)
    {
        $config = Config::get('lc.auth.api');

        $userId  = Auth::$userId;
        if (empty($userId)) {
            return $next($request);
        }
        $action  = $request->action();
        $lockKey = env('id') . "_user_lock_{$action}_{$userId}";
        $redis   = Redis::instance();
        $redis->select(Config::get('lc.redis.db'));
        if ($redis->get($lockKey)) {
            return Response::fail('请求频繁，稍后再试。');
        }
        $redis->setex($lockKey, $config['lock_time'] ?? 3, time());
        $response = $next($request);

        return $response;
    }
}